function showLoading(msg) {
    if (msg == null)
        msg = "正在加载数据...";
    $.blockUI({ css: {
        border: 'none',
        padding: '15px',
        backgroundColor: '#000',
        '-webkit-border-radius': '10px',
        '-moz-border-radius': '10px',
        opacity: .2,
        color: '#fff'
    }, message: msg});
}

function closeLoading() {
    $.unblockUI();
}

/*--获取网页传递的参数--*/
function requestUrlPara(paras) {
    var url = location.href;
    var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
    var paraObj = {}
    for (i = 0; j = paraString[i]; i++) {
        paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
    }
    var returnValue = paraObj[paras.toLowerCase()];
    if (typeof (returnValue) == "undefined") {   //typeof常用来判断一个对象是否为空
        return "";
    } else {
        return returnValue;
    }
}

function getParamStr(url_params, paras) {
    var paraString = url_params.split("!");
    var paraObj = {}
    for (i = 0; j = paraString[i]; i++) {
        if (paraString[i] != '')
            paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
    }
    var returnValue = paraObj[paras.toLowerCase()];
    if (typeof (returnValue) == "undefined") {   //typeof常用来判断一个对象是否为空
        return "";
    } else {
        return returnValue;
    }
}

//打印
function OpenPrint(printUrl) {
    parent.$('#openPrintDiv').dialog({
        title: '打印单据',
        width: 795,
        height: 400,
        closed: false,
        cache: false,
        modal: true,
        button: null
    });
    parent.$('#openPrintIframe')[0].src = printUrl;
    parent.$('#openPrintDiv').dialog('open');
}

// 根据下拉列表的值生成html
function genSelectHtml(selectId, optionList, selectValue, className, style) {
    var sb = [];
    sb[sb.length] = '<select name="' + selectId + '" id="' + selectId + '" class="' + className + '"  style="' + style + '" >';
    for (var n = 0; n < optionList.length; n++) {
        var option = optionList[n];
        if (option["Value"] == selectId) {
            sb[sb.length] = '<option selected="selected" isdecimal="' + option["IsDecimal"] + '" value="' + option["Value"] + '">' + replaceHtmlTag(option["Text"]) + '</option>'
        } else {
            sb[sb.length] = '<option isdecimal="' + option["IsDecimal"] + '" value="' + option["Value"] + '">' + replaceHtmlTag(option["Text"]) + '</option>'
        }
    }
    sb[sb.length] = '</select>'
    return sb.join("");
}

function genSelectListAndDefaultHtml(selectId, optionList, className, style) {
    var sb = [];
    sb[sb.length] = '<select name="' + selectId + '" id="' + selectId + '" class="' + className + '"  style="' + style + '" >';
    for (var n = 0; n < optionList.length; n++) {
        var option = optionList[n];
        if (option["DefaultOption"] != undefined) {
            if (option["DefaultOption"] == "1") {
                sb[sb.length] = '<option selected="selected" value="' + option["Value"] + '">' + replaceHtmlTag(option["Text"]) + '</option>';
            } else {
                sb[sb.length] = '<option value="' + option["Value"] + '">' + replaceHtmlTag(option["Text"]) + '</option>';
            }
        } else {
            sb[sb.length] = '<option value="' + option["Value"] + '">' + replaceHtmlTag(option["Text"]) + '</option>';
        }
    }
    sb[sb.length] = '</select>'
    return sb.join("");
}


//指定操作代码的权限验证
function checkPermByCode(permCode) {
    var resName = window.location.href.split('/')[3];
    var zresult = true;
//    $.ajax({
//        dataType: "json",
//        data: {
//            permCodeList: permCode,
//            resName: resName
//        },
//        url: "/HomePage/CheckPerm/",
//        cache: false,
//        type: "post",
//        async: false,
//        success: function (data) {
//            if (data.Data.length > 0) {
//                zresult = data.Data[0]["IsAudit"];
//            }
//        },
//        error: function () {
//            window.location.href = '/error.html';
//        }
//    });
    return zresult;
}

//选择商品修改选择的行
//busiAction:Sale：销售单；Buy：进货单
var selectWP_url = '';
function SelectWareProductByBusi(obj, busiAction, warehouseId, snManage) {
    parent.$('#openFrameDiv').dialog({
        title: '选择商品',
        width: 1000,
        height: 600,
        closed: false,
        cache: false,
        modal: true,
        maximizable: true,
        resizable: true,
        buttons: [
            {
                text: '确定',
                handler: function () {
                    try {
                        var isAdd = parent.$('#openIframe')[0].contentWindow.$("#hidShareAdd").val();
                        if (isAdd == "shareAdd") {
                            parent.$('#openIframe')[0].contentWindow.saveData();
                        }
                        else {
                            var tempJson = parent.$('#openIframe')[0].contentWindow.initData();
//                            if (snManage != 0) {
//                                SelectSerialNo(tempJson, warehouseId, busiAction);
//                            }
                            parent.$("#tabs .panel:visible iframe")[0].contentWindow.SelectProductOK(tempJson, obj);
                            parent.$('#openFrameDiv').dialog('close');
                        }
                    } catch (e) {
                        alert(e);
                    }
                }
            },
            {
                text: '取消',
                handler: function () {
                    var isAdd = parent.$('#openIframe')[0].contentWindow.$("#hidShareAdd").val();
                    if (isAdd == "shareAdd") {
                        parent.$('#openIframe')[0].contentWindow.window.location = "HomePage/SelectProducts.html?WarehouseId=" + warehouseId + "&BusiAction=" + busiAction;
                    }
                    else {
                        parent.$('#openFrameDiv').dialog('close')
                    }
                }
            }
        ]
    });
    if (selectWP_url != "HomePage/SelectProducts.html?WarehouseId=" + warehouseId + "&BusiAction=" + busiAction) {
        selectWP_url = "HomePage/SelectProducts.html?WarehouseId=" + warehouseId + "&BusiAction=" + busiAction + "&nowTime=" + (new Date().getTime());
        parent.$('#openIframe')[0].src = selectWP_url;
    }
    parent.$('#openFrameDiv').dialog('open');
}

function MVCPage(queryPara) {
    //URL
    var url = location.href;
    var xindex = url.indexOf("#");
    if (xindex != -1) {
        url = url.substring(0, url.indexOf("#"));
    }
    var pindex = url.indexOf("IsPrint=1");
    if (pindex != -1) {
        url = url.replace("IsPrint=1", "");
    }
    var pindex = url.indexOf("isprint=1");
    if (pindex != -1) {
        url = url.replace("isprint=1", "");
    }
    //URL参数
    var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
    //重构URL参数
    var paraObj = {};
    for (i = 0; j = paraString[i]; i++) {
        paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
    }
    for (var i = 0; i < queryPara.length; i++) {
        paraObj[queryPara[i]["name"].toLowerCase()] = queryPara[i]["value"];
    }
    var strUrlPara = '';
    for (var key in paraObj) {
        strUrlPara = strUrlPara + key + "=" + escape(paraObj[key]) + "&";
    }
    if (strUrlPara != '') {
        strUrlPara = strUrlPara.substring(0, strUrlPara.length - 1);
    }
    window.location.href = '?' + strUrlPara;
}

//选择序列号
//busiAction: Sale：销售单；Buy：进货单
function SelectSerialNo(tempJson, warehouseId, busiAction) {
    //商品编号（逗号隔开）
    var strProductIds = '';
    //行号guid
    var strRowIds = '';
    //只要选择的商品中有序列号管理启用必填的就弹窗
    for (var i = 0; i < tempJson.length; i++) {
        if (tempJson[i]["SNManage"] == "1") {
            tempJson[i]["RowId"] = guidGenerator();
            strProductIds = strProductIds + tempJson[i]["ID"] + ",";
            strRowIds = strRowIds + tempJson[i]["RowId"] + ',';
        }
        if (tempJson[i]["SNManage"] == "2") {
            tempJson[i]["RowId"] = guidGenerator();
        }
    }
    if (strProductIds != '') {
        if (busiAction == "Sale") {
            parent.$('#SNManageDIV').dialog({
                title: '序列号管理',
                width: 900,
                height: 530,
                closed: false,
                cache: false,
                modal: true,
                maximizable: true,
                resizable: true,
                buttons: null
            });
            parent.$('#openSNManageIframe')[0].src = "/HomePage/SelectSN?ProductIds=" + strProductIds + "&WarehouseId=" + warehouseId + "&RowIds=" + strRowIds;
            parent.$('#SNManageDIV').dialog('open');
        }
        if (busiAction == "Buy") {
            parent.$('#SNManageDIV').dialog({
                title: '序列号管理',
                width: 600,
                height: 580,
                closed: false,
                cache: false,
                modal: true,
                maximizable: true,
                resizable: true,
                buttons: null
            });
            // 商品名称组   商品ID组  仓库名称  业务类型（用来标识第一参数是仓库还是商品  0：仓库 1：商品）   仓库ID   商品单位

            parent.$('#openSNManageIframe')[0].src = "/HomePage/BillSNManage?ProductIds=" + strProductIds
                + "&WarehouseId=" + warehouseId
                + "&RowIds=" + strRowIds;

            parent.$('#SNManageDIV').dialog('open');
        }
    }
}

//盘点序列号
//单据id，单据明细id，商品id，仓库id，允许序列号数（选填),盘点类型type（1，第一次盘点；2，后期盘点),snMange(1.必填；2.选填）
function PDSerialNo(takBillId, takId, productId, warehouseId, allowCount, type) {
    if (productId != '') {
        parent.$('#SNManageDIV').dialog({
            title: '盘点序列号',
            width: 900,
            height: 560,
            closed: false,
            cache: false,
            modal: true,
            maximizable: false,
            resizable: true,
            buttons: null
        });
        parent.$('#openSNManageIframe')[0].src = "HomePage/PDSN.html?ProductIds=" + productId + "&WarehouseId=" + warehouseId
            + "&TakBillId=" + takBillId + "&TakId=" + takId + "&allowCount=" + allowCount + "&storeType=" + type;//+"&snManage="+snManage;
        parent.$('#SNManageDIV').dialog('open');
    }
}

//单行商品选择序列号
//busiAction: Sale：销售单；Buy：进货单   flag用于判断传值的页面
function SingleSelectSerialNo(productId, RowId, warehouseId, busiAction, flag, strProductNames, strProductUnits, strProductForms, strProductStocks) {
    if (productId != '' && RowId != '') {
        if (busiAction == "Sale") {
            parent.$('#SNManageDIV').dialog({
                title: '序列号管理',
                width: 900,
                height: 530,
                closed: false,
                cache: false,
                modal: true,
                maximizable: true,
                resizable: true,
                buttons: null
            });
            parent.$('#openSNManageIframe')[0].src = "HomePage/SelectProductSN.html?ProductIds=" + productId + "&WarehouseId=" + warehouseId + "&RowIds=" + RowId + "&flag=" + flag + "&busiAction=" + busiAction;
            parent.$('#SNManageDIV').dialog('open');
        } else if (busiAction == "Buy" || busiAction == "SaleReturn") {
            parent.$('#SNManageDIV').dialog({
                title: '序列号管理',
                width: 600,
                height: 580,
                closed: false,
                cache: false,
                modal: true,
                maximizable: true,
                resizable: true,
                buttons: null
            });
            //商品名称规格
            /* var ProductName = $("#ProductName").val();
             var ProductForm = $("#ProductForm").val();
             var ProductUnit = $("#UnitName").find("option:selected").text();
             var productId;
             if ($("#ProductId").val() != "") {
             productId = $("#ProductId").val();*/
            parent.$('#openSNManageIframe')[0].src = "HomePage/SNManage.html?" +
                "ProductIds=" + productId
                + "&WarehouseId=" + warehouseId + ','
                + "&warehouseStocks=" + strProductStocks
                + "&ProductName=" + escape(strProductNames)
                + "&UnitName=" + escape(strProductUnits)
                + "&ProductForm=" + escape(strProductForms)
                + "&RowIds=" + RowId
                + "&flag=" + flag
                + "&sobState= 1";

            parent.$('#SNManageDIV').dialog('open');
        } else if (busiAction == "Transfer" || busiAction == "BuyReturn") {
            parent.$('#SNManageDIV').dialog({
                title: '序列号管理',
                width: 900,
                height: 530,
                closed: false,
                cache: false,
                modal: true,
                maximizable: true,
                resizable: true,
                buttons: null
            });
            parent.$('#openSNManageIframe')[0].src = "HomePage/SelectProductSN.html?ProductIds=" + productId + "&WarehouseId=" + warehouseId + "&RowIds=" + RowId + "&flag=" + flag + "&busiAction=" + busiAction;
            parent.$('#SNManageDIV').dialog('open');
        }
    }
}

//单个checkbox点击
function ChooseGoods(obj, pid, count, serialId, serialNo, serialremark, productSn) {
    var chooseGoods;
    var BusiAction = requestUrlPara("BusiAction");
    if (count == "") {
        count = 0;
    }
    chooseGoods = parent.$("#tabs .panel:visible iframe")[0].contentWindow.$("#hid" + BusiAction + "ChooseGoods").val();
    var checkState = $(obj).attr("checked");
    if (checkState) {//选中
        if ($(obj).parent().find("input[name='hidSNManage']").val() == "1" && productSn == "1") {
            GetSerialNo($(obj).parent().parent().children("td").eq(9).find("input[name='TxgoodsNum']"), pid);
            return;
        }
        if (count == 0) {
            count = 1;
        }
        $(obj).parent().parent().children('td').eq(9).find("input[name='TxgoodsNum']").val(count).change();

        if (chooseGoods.indexOf(itemStr) < 0) {
            var itemStr = pid + "|" + count + "|" + serialId + "|" + serialNo + "|" + serialremark;
            chooseGoods = chooseGoods + "," + itemStr;
            parent.$("#tabs .panel:visible iframe")[0].contentWindow.$("#hid" + BusiAction + "ChooseGoods").val(chooseGoods);
        }
    }
    else {//取消
        if (chooseGoods.indexOf(pid) >= 0) {
            var goodsArr = new Array();
            goodsArr = chooseGoods.split(',');
            var n = -1;
            for (var i = 0; i < goodsArr.length; i++) {
                var temp = "";
                temp = goodsArr[i];
                if (temp.indexOf(pid) >= 0) {
                    n = i;
                    break;
                }
            }
            if (n >= 0) {
                goodsArr.splice(n, 1)
            }
            $(obj).parent().parent().children('td').eq(9).find("input[name='TxgoodsNum']").val("").change();
            $(obj).parent().find("input[name='hidSerialId']").val("");
            $(obj).parent().find("input[name='hidSerialNo']").val("");
            $(obj).parent().find("input[name='hidSerialRemarks']").val("");
            parent.$("#tabs .panel:visible iframe")[0].contentWindow.$("#hid" + BusiAction + "ChooseGoods").val(goodsArr.join(',')).change();
        }
    }
//    SumGoodsNum();
}

function SumGoodsNum() {
    var BusiAction = requestUrlPara("BusiAction");
    var chooseGoods = parent.$("#tabs .panel:visible iframe")[0].contentWindow.$("#hid" + BusiAction + "ChooseGoods").val().split(',');
    var SumGoodsCount = 0;
    $.each(chooseGoods, function (n, value) {
        if (value != "") {
//            var newArr = new Array();
//            newArr = value.split('|');
            SumGoodsCount = SumGoodsCount + 1;
        }
    });
    $("#spanGoodsNum").text(SumGoodsCount);
}

//单行商品选择序列号
//busiAction: Sale：销售单；Buy：进货单
function SingleSelectSerialNoByAllow(productId, RowId, warehouseId, busiAction, allowCount) {
    if (productId != '' && RowId != '') {
        if (busiAction == "Sale") {
            parent.$('#SNManageDIV').dialog({
                title: '序列号管理',
                width: 900,
                height: 530,
                closed: false,
                cache: false,
                modal: true,
                maximizable: true,
                resizable: true,
                buttons: null
            });
            parent.$('#openSNManageIframe')[0].src = "/HomePage/SelectSN?ProductIds=" + productId + "&WarehouseId=" + warehouseId + "&RowIds=" + RowId + "&allowCount=" + allowCount;
            parent.$('#SNManageDIV').dialog('open');
        }
        if (busiAction == "Buy") {
            parent.$('#SNManageDIV').dialog({
                title: '序列号管理',
                width: 600,
                height: 580,
                closed: false,
                cache: false,
                modal: true,
                maximizable: true,
                resizable: true,
                buttons: null
            });
            // 商品名称组   商品ID组  仓库名称  业务类型（用来标识第一参数是仓库还是商品  0：仓库 1：商品）   仓库ID   商品单位

            parent.$('#openSNManageIframe')[0].src = "/HomePage/BillSNManage?ProductIds=" + productId
                + "&WarehouseId=" + warehouseId
                + "&RowIds=" + RowId
                + "&allowCount=" + allowCount;

            parent.$('#SNManageDIV').dialog('open');
        }
    }
}

//guid生成
function guidGenerator() {
    var S4 = function () {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

function closethistab(tabname) {
    parent.$.messager.defaults = {
        ok: "确定",
        cancel: "取消"
    };
    parent.$.messager.confirm('系统提示', '提示：确定要关闭当前页面吗？', function (r) {
        if (r) {
            parent.CloseTabByTitle(tabname);
        }
    });
}
function unLockState() {
    parent.$.extend(parent.$.messager.defaults, {
        ok: "去解锁",
        cancel: "取消"
    });
    parent.$.messager.confirm('系统提示', '提示：当前帐套已锁定，请先解锁帐套！', function (r) {
        if (r) {
            parent.childAddTab('历史盘点', 'StoreReserve/List.html', '慧管货');
        }
    });
    parent.$.extend(parent.$.messager.defaults, {
        ok: "确定",
        cancel: "取消"
    });
}

//检查权限
function checkAuthority(url) {
   
	var result = true;
    
    $.ajax({
    	dataType:"json",
    	data:{
    		"Url":url
    	},
    	url:"/Common/checkAuthority.json",
    	cache:false,
    	type:"post",
    	async:false,
    	success:function(data){
    		result = true; 
    	},
    	error:function(){
    		result = false;
    	}
    });
    return result;
}
//
//function showLoadingState(obj) {
//    obj.$("#divLoading").show();
//}
//
//function closeLoadingState(obj) {
//    obj.$("#divLoading").hide();
//}


function showSnList() {
    $(".sn").hover(function () {
        $(this).find('.snList').show();

    }, function () {
        $(this).find('.snList').hide();
    });
}

//验证序列号是否重复
function varlidatorSerialNo(nodeName) {
    var serialIdList = $("input:hidden[name='" + nodeName + "']");
    var serialList = [];
    if (serialIdList != undefined && serialIdList != null) {
        for (var i = 0; i < serialIdList.length; i++) {
            var noList = serialIdList[i].value.split(",");
            for (var j = 0; j < noList.length; j++) {
                if (noList[j] != "") {
                    serialList.push(noList[j]);
                }
            }
        }
    }
    if (isRepeat(serialList)) {
        return false;
    }
    return true;
}

